package com.myself.ssoserver.service

import com.myself.ssoserver.dto.AuthException
import com.myself.ssoserver.dto.AuthRequest
import com.myself.ssoserver.dto.AuthResponse
import org.springframework.stereotype.Service
import com.myself.ssoserver.utils.PasswordUtils
@Service
class AuthService(
    private val userService: UserService,
    private val historyService: LoginHistoryService,
    private val sessionService: SessionService
) {
    fun login(request: AuthRequest, clientIp: String, userAgent: String?): AuthResponse {
        val user = userService.findByUsername(request.username)
            ?: throw AuthException("用户不存在")
        if (user.isActive != 1){
            throw AuthException("用户不可用,请联系管理员")
        }
        if (!PasswordUtils.matches(request.password, user.password)) {
            throw AuthException("密码错误")
        }

        // 记录登录历史
        historyService.recordLogin(user.id, clientIp, userAgent)

        // 更新最后登录IP
        userService.updateLastLogin(user.id, clientIp)

        return AuthResponse(
            token = sessionService.createSession(user, clientIp),
            userId = user.id,
            username = user.username,
            user = user
        )
    }
}